package com.ionehe.conf;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.sql.SQLException;

@Configuration
@MapperScan(basePackages = RabbitProducerDataSourceConfiguration.PACKAGE, sqlSessionFactoryRef = "rabbitProducerSqlSessionFactory")
@PropertySource({"classpath:rabbit-producer-message.properties"})
public class RabbitProducerDataSourceConfiguration {
     
    private static Logger LOGGER = org.slf4j.LoggerFactory.getLogger(RabbitProducerDataSourceConfiguration.class);

    static final String PACKAGE = "com.ionehe.dao";
    static final String MAPPER_LOCATION = "classpath:com/ionehe/dao/*.xml";

    @Value("${rabbit.producer.druid.type}")
    private Class<? extends DataSource> dataSourceType;
     
    @Bean(name = "rabbitProducerDataSource")
    @Primary
    @ConfigurationProperties(prefix = "rabbit.producer.druid.jdbc")
    public DataSource rabbitProducerDataSource() throws SQLException {
        DataSource rabbitProducerDataSource = DataSourceBuilder.create().type(dataSourceType).build();
        LOGGER.info("============= rabbitProducerDataSource : {} ================", rabbitProducerDataSource);
        return rabbitProducerDataSource;
    }


    @Bean(name = "rabbitProducerSqlSessionFactory")
    @Primary
    public SqlSessionFactory rabbitProducerSqlSessionFactory(@Qualifier("rabbitProducerDataSource") DataSource brmDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(brmDataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(MAPPER_LOCATION));
        return sessionFactory.getObject();
    }

    //
    //public DataSourceProperties primaryDataSourceProperties(){
    //    return new DataSourceProperties();
    //}
    //
    //public DataSource primaryDataSource(){
    //    return primaryDataSourceProperties().initializeDataSourceBuilder().build();
    //}
     
}